<template>
	<view>
		<view class="search-box">
			<uni-search-bar @input="input" :radius="100" cancel-button="none"></uni-search-bar>
		</view>
		
		<view class="search-list" v-if="searchList.length!==0">
			<view class="search-list-item" v-for="(item,index) in searchList" :key="index" @click="toDetail(item)">
				<text>{{item.goods_name}}</text>
				<uni-icons type="arrowright" size="16px"></uni-icons>
			</view>
		</view>
		
		<view class="history-box" v-else>
			<view class="history-title">
				<text>搜索历史</text>
				<uni-icons type="trash" size="17px" @click="clean()"></uni-icons>
			</view>
			
			<view class="history-list">
				<uni-tag :text="item" v-for="(item,index) in histories" :key="index" @click="toGoodList(item)"></uni-tag>
			</view>
		</view>
		
	</view>
	
</template>

<script>
	export default {
		data() {
			return {
				searchList:[],
				historyList:[],
				timer:null,
				result:""
			};
		},
		onLoad() {
			this.historyList=JSON.parse(uni.getStorageSync('result')||'[]')
		},
		methods:{
			input(e){
				
				clearTimeout(this.timer)
				
				this.timer=setTimeout(()=>{
					this.result=e,
					this.getSearchList(),
					this.saveHistory()
				},500)
				
			},
			async getSearchList(){
				
				if(this.result.length===0){
					this.searchList=[]
					return
				}
				
				const {data:res} = await uni.$http.get('/api/public/v1/goods/qsearch',{query:this.result})
				if(res.meta.status!=200) return uni.$showMsg()
				this.searchList=res.message
				
			},
			toDetail(item){
				uni.navigateTo({
					url:'/subpackges/detail/detail?goods_id='+item.goods_id
				})
			},
			saveHistory(){
				// this.historyList.push(this.result)
				const set =new Set(this.historyList)
				set.delete(this.result)
				set.add(this.result)
				
				this.historyList=Array.from(set)
				
				uni.setStorageSync('result', JSON.stringify(this.historyList))
			},
			clean(){
				this.historyList=[]
				uni.setStorageSync('result','[]')
			},
			toGoodList(item){
				uni.navigateTo({
					url:'/subpackges/list/list?query='+item
				})
			}
		},
		computed:{
			histories(){
				return [...this.historyList].reverse()
			}
		}
	}
</script>

<style lang="scss">
	.search-box{
		position: sticky;
		top: 0;
		z-index: 999;
	}
	.search-list{
		padding: 0 5px;
		.search-list-item{
			font-size: 15px;
			padding: 20px 0;
			border-bottom: 1px solid #efefef;
			display: flex;
			align-items: center;
			justify-content: space-between;
			text{
				//不允许换行
				white-space: nowrap;
				//隐藏溢出
				overflow: hidden;
				//溢出用...代替
				text-overflow: ellipsis;
				margin-right: 3px;
			}
		}
	}
	.history-box{
		padding: 0 5px;
		.history-title{
			display: flex;
			justify-content: space-between;
			height: 40px;
			align-items: center;
			border-bottom: 1px solid #efefef;
			text{
				font-size: 15px;
			}
		}
		.history-list{
			display: flex;
			flex-wrap: wrap;
			.uni-tag{
				display: block;
				margin-top: 5px;
				margin-right: 10px;
			}
			
		}
		
	}
</style>
